import store from '@/store'

export function setPopShow (switchType, type, data, onClose) {
  const popData = { type, data, onClose }
  const state = store.state.pops

  if (switchType === 'open') {
    // 检查是否存在相同 type
    const existingPopIndex = state.popShow.findIndex(item => item.type === popData.type)
    if (existingPopIndex !== -1) {
      // 如果存在,更新数据和onClose方法
      state.popShow[existingPopIndex] = popData
    } else {
      // 如果不存在,添加新的
      state.popShow.push(popData)
    }
    store.commit('pops/popShow', [...state.popShow])
  } else {
    // 关闭弹窗
    const closingPop = state.popShow.find(item => item.type === type)
    if (closingPop && typeof closingPop.onClose === 'function') {
      // 如果存在onClose方法,调用它
      closingPop.onClose(data)
    }
    // 过滤掉指定 type 的元素
    const newPopShow = state.popShow.filter(item => item.type !== type)
    store.commit('pops/popShow', newPopShow)
  }

  // #ifdef H5
  bodyHide()
  // #endif
}

export function getPopData (type) {
  const popShow = store.state.pops.popShow || []
  const target = popShow.find(item => item.type === type)
  return target ? target.data : null
}

function bodyHide () {
  const popShow = store.state.pops.popShow
  const dom = document.querySelector('body')
  if (popShow.length > 0) {
    dom.classList.add('hid')
    dom.style.overflow = 'hidden'
  } else {
    dom.classList.remove('hid')
    dom.style.overflow = ''
  }
}
